﻿using AhpilyServer;
using AhpilyServer.Concurrent;
using GameServer.Model;

namespace GameServer.Cache
{
    public class AccountCache
    {
        #region account model cache
        private Dictionary<string, AccountModel> dictAccountModel = [];
        private ConcurrentInt id = new(-1);
        /// <summary>
        /// 账号是否存在
        /// </summary>
        public bool IsExist(string account)
        {
            return dictAccountModel.ContainsKey(account);
        }
        /// <summary>
        /// 创建新的账号数据模型
        /// </summary>
        public void Create(string account, string password)
        {
            AccountModel model = new(id.Add_Get(), account, password);
            dictAccountModel.Add(account, model);
        }
        /// <summary>
        /// 获取账号对应的数据模型
        /// </summary>
        public AccountModel GetModel(string account)
        {
            return dictAccountModel[account];
        }
        /// <summary>
        /// 账号密码是否匹配
        /// </summary>
        public bool IsMatch(string account, string password)
        {
            AccountModel model = dictAccountModel[account];
            return model.Password == password;
        }
        #endregion
        #region account client cache
        private Dictionary<string, ClientPeer> dictAccountClient = [];
        private Dictionary<ClientPeer, string> dictClientAccount = [];
        /// <summary>
        /// 是否在线
        /// </summary>
        public bool IsOnline(string account)
        {
            return dictAccountClient.ContainsKey(account);
        }
        /// <summary>
        /// 是否在线
        /// </summary>
        public bool IsOnline(ClientPeer client)
        {
            return dictClientAccount.ContainsKey(client);
        }
        /// <summary>
        /// 用户上线 添加缓存
        /// </summary>
        public void Online(string account, ClientPeer client)
        {
            dictAccountClient.Add(account, client);
            dictClientAccount.Add(client, account);
        }
        /// <summary>
        /// 用户下线 清理缓存
        /// </summary>
        public void Offline(string account)
        {
            ClientPeer client = dictAccountClient[account];
            dictClientAccount.Remove(client);
            dictAccountClient.Remove(account);
        }
        /// <summary>
        /// 用户下线 清理缓存
        /// </summary>
        public void Offline(ClientPeer client)
        {
            string account = dictClientAccount[client];
            dictClientAccount.Remove(client);
            dictAccountClient.Remove(account);
        }
        /// <summary>
        /// 获取在线玩家ID
        /// </summary>
        public int GetId(ClientPeer client)
        {
            string account = dictClientAccount[client];
            AccountModel model = dictAccountModel[account];
            return model.Id;
        }
        #endregion
    }
}
